from django.shortcuts import HttpResponse, render, redirect
from app01 import models
from django.views.decorators.csrf import csrf_exempt

"""
    部门管理
"""


# 部门管理 S
def depart_list(request):
    """部门列表数据获取"""
    # [{},{},{}]
    data_list = models.Deptartment.objects.all()
    return render(request, 'depart/list.html', {"data_list": data_list})


def depart_add(request):
    """添加部门"""
    if request.method == 'GET':
        return render(request, 'depart/add.html')
    # 获取用户post提交过来的数据
    title = request.POST.get('depart_name')
    models.Deptartment.objects.create(title=title)
    return redirect('/depart/list/')


def depart_edit(request, depart_id):
    """编辑部门信息"""
    # 找到编辑记录数据
    if request.method == 'GET':
        row_obj = models.Deptartment.objects.filter(id=depart_id).first()
        # print(row_obj.id,row_obj_title)
        return render(request, 'depart/edit.html', {"row_obj": row_obj})

    title = request.POST.get('depart_name')
    models.Deptartment.objects.filter(id=depart_id).update(title=title)
    return redirect('/depart/list/')


def depart_delete(request):
    """删除部门"""
    depart_id = request.GET.get('depart_id')
    models.Deptartment.objects.filter(id=depart_id).delete()
    return redirect('/depart/list/')


@csrf_exempt
def depart_multi(request):
    """
        基于EXCEL文件批量上传，创建部门
    """
    if request.method == 'GET':
        data_list = models.Deptartment.objects.all()
        return render(request, 'depart/list.html', {"data_list": data_list})
    if request.method == 'POST':
        # 1、获取用户上传的文件对象
        file_obj = request.FILES.get('files')
        print(type(file_obj))  # 通过 这样可用知道 它是用了什么
        # from django.core.files.uploadedfile import InMemoryUploadedFile
        print(file_obj.name)  # 文件名 xxx.xlsx
        # 2、传递文件对象，给openpyxl 打开Excel并读取内容
        from openpyxl import load_workbook
        wb = load_workbook(file_obj)
        sheet = wb.worksheets[0]
        cell = sheet.cell(row=1, column=1)  # 第1行第1列
        print(cell.value)
        # 3、循环获取每一行数据,从第2行开始,第1行是标题
        for row in sheet.iter_rows(min_row=2):
            # print(row) # (<Cell 'Sheet1'.A2>,)
            # print(row[0].value)# xx部门
            dept_name = row[0].value
            is_exists = models.Deptartment.objects.filter(title=dept_name).exists()
            if not is_exists:
                models.Deptartment.objects.create(title=dept_name)
                print(f'{dept_name},已创建')
            else:
                print(f'{dept_name},已经存在')
        return HttpResponse('上传文件')
